/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.atomojo.sparql;

import java.net.URI;
import java.util.Set;
import java.util.TreeSet;

/**
 *
 * @author alex
 */
public class SelectQuery extends Query {

   boolean returnAll;
   Set<String> returnSet;
   public SelectQuery(Prologue prologue)
   {
      super(prologue);
      returnSet = new TreeSet<String>();
      returnAll = false;
   }
   
   public Set<String> getReturnVariables() {
      return returnSet;
   }
   
   public void setReturnAll(boolean flag) {
      returnAll = flag;
   }
   
   public void resolve() {
      if (returnAll) {
         // find all variables and add to returnSet
         for (Triple triple : whereClause.getClauses()) {
            Ref ref = triple.getSubject();
            if (ref instanceof VariableRef) {
               String name = ((VariableRef)ref).getName();
               if (!returnSet.contains(name)) {
                  returnSet.add(name);
               }
            }
            ref = triple.getPredicate();
            if (ref instanceof VariableRef) {
               String name = ((VariableRef)ref).getName();
               if (!returnSet.contains(name)) {
                  returnSet.add(name);
               }
            }
            ref = triple.getObject();
            if (ref instanceof VariableRef) {
               String name = ((VariableRef)ref).getName();
               if (!returnSet.contains(name)) {
                  returnSet.add(name);
               }
            }
         }
      }
   }
   
   public String toString() {
      StringBuilder builder = new StringBuilder();
      builder.append(prologue.toString());
      builder.append("SELECT ");
      if (returnAll) {
         builder.append("*");
      } else {
         boolean first = true;
         for (String name : returnSet) {
            if (!first) {
               builder.append(",");
            }
            first = false;
            builder.append("?");
            builder.append(name);
         }
      }
      if (whereClause!=null) {
         builder.append("\n");
         builder.append(whereClause);
      }
      return builder.toString();
   }
   
   
}
